import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/Api/LoginApi.dart';
import 'package:flutter_app/HomeActivity.dart';
import 'package:flutter_app/ServerManage.dart';
import 'package:flutter_app/Utils/Constants.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'Utils/DioUtils.dart';

class LoginActivity extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginActivityState();
}

class LoginActivityState extends State<LoginActivity> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _obscureText = true;
  FocusNode unFN = FocusNode();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _scaffoldKey,
        body:
//         SafeArea(
//          top: false,
//          bottom: false,
//          child:
            Column(
          children: <Widget>[
            SizedBox(
              height: 180.0,
              child: Image.asset(
                'images/logo.png',
                width: 100.0,
                height: 100.0,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(20.0),
              child: Column(
                children: <Widget>[
                  TextField(
                    controller: _userNameController,
                    autofocus: true,
                    decoration: InputDecoration(
                      border: UnderlineInputBorder(),
                      filled: true,
                      fillColor: Color(0xFAFAFA),
                      labelText: '账号',
                      hintText: '请输入账号',
                      suffixIcon: GestureDetector(
                        onTap: () {
                          setState(() {
                            _userNameController.clear();
                          });
                        },
                        child: Icon(Icons.highlight_off),
                      ),
                    ),
//                    keyboardType: TextInputType.phone,
//                    maxLength: 13,
                    focusNode: unFN,
//                    inputFormatters: <TextInputFormatter>[
//                      WhitelistingTextInputFormatter.digitsOnly,
//                      _UsNumberTextInputFormatter(),
//                    ],
                  ),
                  TextField(
                    controller: _passwordController,
                    decoration: InputDecoration(
                      border: UnderlineInputBorder(),
                      filled: true,
                      fillColor: Color(0xFAFAFA),
                      labelText: '密码',
                      hintText: '请输入密码',
                      suffixIcon: GestureDetector(
                        onTap: () {
                          setState(() {
                            _obscureText = !_obscureText;
                          });
                        },
                        child: Icon(_obscureText
                            ? Icons.visibility
                            : Icons.visibility_off),
                      ),
                    ),
                    maxLength: 13,
//                          focusNode: unFN,
                    obscureText: _obscureText,
                    onSubmitted: (String value) {
                      setState(() {
                        person.password = value;
                      });
                    },
                  ),
                  SizedBox(height: 50.0),
                  Container(
                    child: RaisedButton(
                      color: Colors.blue[400],
                      child: Row(
                        children: <Widget>[
                          Expanded(child: Text('')),
                          Padding(
                            padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                            child: Text(
                              '登 录',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16.0,
                              ),
                            ),
                          ),
                          Expanded(child: Text('')),
                        ],
                      ),
                      onPressed: _handleSubmitted,
                    ),
                  ),
                  SizedBox(
                    height: 15.0,
                  ),
                  Row(
                    children: <Widget>[
                      InkWell(
                        child: Text(
                          '找回密码',
                          style: TextStyle(
                            decoration: TextDecoration.underline,
                            fontSize: 15.0,
                            color: Colors.blue,
                          ),
                        ),
                        onTap: () {
                          _findPWD();
                        },
                      ),
                      Expanded(child: Text('')),
                      InkWell(
                        child: Text(
                          '切换网络',
                          style: TextStyle(
                            fontSize: 15.0,
                            color: Colors.blue,
                          ),
                        ),
                        onTap: () {
                          showInSnackBar('无可以切换的网络');
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Expanded(child: Text('')),
            Padding(
              padding: EdgeInsets.only(bottom: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(child: Text('')),
                  FlatButton(
                    child: Text(
                      '设置服务器',
                      style: TextStyle(
//                        color: Colors.blue,
                        fontSize: 15.0,
                      ),
                    ),
                    textColor: Colors.blue,
                    onPressed: () {
                      Navigator.push(context, MaterialPageRoute<void>(
                        builder: (BuildContext context) {
                          return ServerManage();
                        },
                      ));
                    },
                  ),
                  Text(
                    '|',
                    style: TextStyle(
                      color: Colors.blue,
                    ),
                  ),
                  FlatButton(
                    child: Text(
                      '退      出',
                      style: TextStyle(
                        color: Colors.blue,
                        fontSize: 15.0,
                      ),
                    ),
                    onPressed: _quitApp,
                  ),
                  Expanded(child: Text('')),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  PersonData person = PersonData();
  final TextEditingController _userNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  String _validatePhoneNumber(String value) {
    final RegExp phoneExp = RegExp('[1][3-9][0-9]{9}');
    if (!phoneExp.hasMatch(value.replaceAll(' ', ''))) return '手机号格式错误.';
    return null;
  }

  Future _handleSubmitted() async {
    unFN.unfocus();
    if (_userNameController.text == '' || _passwordController.text == '') {
      showInSnackBar('请输入账号密码!');
      return;
    }
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    _prefs.setString(Constants.operatorName, _userNameController.text);
//    String str = _validatePhoneNumber(_userNameController.text);
//    if (str != null) {
//      showInSnackBar('$str');
//    } else {
//      showInSnackBar(
//          '${_userNameController.text}\'s password is ${_passwordController
//              .text}');
//    }
    Response response = await DioUtils().instance().post(
        'http://' + _prefs.getString(Constants.url) + '/job.aspx',
        data: await login(_passwordController.text));
    Map<String, dynamic> resp = json.decode(response.data);
    print(resp);
    if (resp['Status'] == '0') {
      ///登录成功
      _prefs.setString(Constants.operatorId, '${resp['Data'][0]['ID']}');
      Navigator.of(context).pushReplacement(
          MaterialPageRoute<void>(builder: (BuildContext context) {
            return HomeActivity();
          }));
    } else {
      ///登录失败
      showInSnackBar(resp['Message']);
    }
  }

  void showInSnackBar(String value) {
    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(value)));
  }

  void _quitApp() {
    SystemNavigator.pop();
  }

  Future<Null> _findPWD() async {
    return showDialog<Null>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
//          title:  Text('Rewind and remember'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text('请联系管理员重置密码.'),
//                 Text('You\’re like me. I’m never satisfied.'),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

class PersonData {
  String username = '';
  String password = '';
}

/// Format incoming numeric text to fit the format of ### #### ####
class _UsNumberTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue value) {
    final int textLength = value.text.length;
    int usedSubstringIndex = 0;
    final StringBuffer text = StringBuffer();
    if (textLength >= 4) {
      text.write(value.text.substring(0, usedSubstringIndex = 3) + ' ');
    }
    if (textLength >= 8) {
      text.write(value.text.substring(3, usedSubstringIndex = 7) + ' ');
    }
    if (textLength >= 11) {
      text.write(value.text.substring(7, usedSubstringIndex = 11));
    }
    // Dump the rest.
    if (textLength >= usedSubstringIndex)
      text.write(value.text.substring(usedSubstringIndex));
    return TextEditingValue(
      text: text.toString(),
      selection: TextSelection.collapsed(offset: text.toString().length),
    );
  }
}
